const router = require("koa-router")();
const jwt = require('jsonwebtoken');
const AccountModel = require("../models/account.js");
const RoomModel = require("../models/room.js");
const ResultHelper = require("../utils/resultHelper.js");
const VerifyHelper = require("../utils/verifyHelper.js");

router.post("/login", async ctx => {
	const {
		phone,
		password
	} = ctx.request.body;
	if (!phone) {
		console.log(ctx)
		return ResultHelper.errInfo422(ctx, "请输入账号")
	}
	if (!password) {
		return ResultHelper.errInfo422(ctx, "请输入密码")
	}
	const item = await AccountModel.findOne({
		phone: ctx.request.body.phone
	});
	
	const room = await RoomModel.findOne({
		user_id: item.id
	});
	console.log(room)
	if (!item) {
		return ResultHelper.errInfo422(ctx, "账号不存在")
	}
	const passwordTrue = item.password; // 输入的密码保存下
	if (passwordTrue != ctx.request.body.password) {
		return ResultHelper.errInfo422(ctx, "密码错误")
	}
	ctx.body = {
		code: 200,
		msg: "登录成功",
		data: {
			token: jwt.sign({
				data: ctx.request.body.username,
				exp: Math.floor(Date.now() / 1000) + (60 * 3600) // 一小时
			}, 'secret'),
			role: item.role,
			phone: item.phone,
			user_id: item.id,
			room_id: room ? room.id : 0,
			house_id: room ? room.house_id : 0
		}
	}
})

router.get("/login/out", async ctx => {
	console.log(ctx.session)
	ctx.body = {
		msg: "密码错误"
	}
})



module.exports = router;